/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/ban-types */
// eslint-disable-next-line react-hooks/exhaustive-deps
import { useEffect, useState } from "react";
import Header from "@/components/Header";
import {
  Input,
  Select,
  Table,
  Button,
  TableColumnsType,
  Form,
  Tag,
  Modal,
  Spin,
  UploadFile,
  UploadProps,
  Row,
  Col,
  Space,
  DatePicker,
} from "antd";
import VehicleForm from "./Form";
import _ from "lodash";
import { DataType } from "./interfaceType";
import { getStore, getVesearch, updateVehicle,addVehicle,updateVehicleRent,uploadImage,deleteVehicle,getVehicle } from "../../../api/index";
export default function MessageVehicle() {
  const columns: TableColumnsType<DataType> = [
    {
      title: "编号",
      width: 90,
      dataIndex: "veid",
      key: "key",
      defaultSortOrder: "ascend", //默认升序
      sorter: (a, b) => a.veid - b.veid,
    },
    {
      title: "车型/照片",
      width: 250,
      dataIndex: "image",
      key: "image",
      render: (imageUrl, record) => {
        const description = record.vname;
        const imageUrlwithslash = imageUrl.replace(/\/upload/, "/upload/");
        return (
          <div style={{ display: "flex", alignItems: "center" }}>
            <img
              src={imageUrlwithslash}
              alt="车型照片"
              style={{
                maxWidth: "90px",
                maxHeight: "100px",
                borderRadius: "5px",
                marginLeft: "10px",
                marginRight: "10px",
              }}
            />
            <p className="text">{description}</p>
          </div>
        );
      },
    },
    {
      title: "车牌",
      width: 100,
      dataIndex: "platenumber",
      key: "platenumber",
    },
    {
      title: "所在门店",
      dataIndex: "name",
      key: "name",
      width: 100,
    },
    {
      title: "当前里程数",
      dataIndex: "mileage",
      key: "mileage",
      width: 100,
    },
    {
      title: "油箱容量",
      dataIndex: "capacity",
      key: "capacity",
      width: 100,
    },
    {
      title: "车身颜色",
      dataIndex: "colour",
      key: "colour",
      width: 100,
    },
    {
      title: "运营状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      render: (_, { vstatus }: any) => {
        return Number(vstatus) === 1 ? (
          <Tag color="green">租凭中</Tag>
        ) : (
          <Tag color="red">未租凭</Tag>
        );
      },
    },
    {
      title: "操作",
      key: "operation",
      fixed: "right",
      width: 110,
      render: (_, record) => {
        return (
          <div>
            <Button
              type="primary"
              style={{ marginBottom: "5px" }}
              onClick={() => showEditModal(record, record.veid)}
            >
              修改信息
            </Button>
            <Button
              style={{ marginBottom: "5px" }}
              onClick={() => hideRent(record.veid)}
            >
              租金设置
            </Button>
            <Button onClick={() => Delete(record.veid)}>删除此车</Button>
          </div>
        );
      },
    },
  ];
  const [list, setList] = useState([]); // 存放车辆信息
  const [store, setStore] = useState<[]>([]); // 存放门店信息
  const [open, setOpen] = useState(false); // 关闭(添加修改)弹框状态
  const [previewOpen, setPreviewOpen] = useState(false); // 预览照片1
  const [previewOpen1, setPreviewOpen1] = useState(false); // 预览照片2
  const [previewOpen2, setPreviewOpen2] = useState(false); // 预览照片2
  const [previewImage, setPreviewImage] = useState(""); // 图片1
  const [previewImage1, setPreviewImage1] = useState(""); // 图片2
  const [previewImage2, setPreviewImage2] = useState(""); // 图片3
  const [fileList, setFileList] = useState<UploadFile[]>([]); // 图片1
  const [fileList1, setFileList1] = useState<UploadFile[]>([]); // 图片2
  const [fileList2, setFileList2] = useState<UploadFile[]>([]); // 图片3
  const [editMode, setEditMode] = useState(false); // 判断是修改还是添加
  const [selectedRecord, setSelectedRecord] = useState<DataType | null>(null); // 表单数据
  const [delVisible, setDelVisible] = useState(false); // 删除
  const [id, setId] = useState(""); // 存放当前id
  const [name, setName] = useState<string>(""); // 搜索(车型名)
  const [vstatus, setVstatus] = useState<string>(""); // 搜索(状态)
  const [sid, setSid] = useState<string>(""); // 搜索(门店)
  const [spinning, setSpinning] = useState(false); // 刷新页面缓冲一秒
  const [rentVisible, setRentVisible] = useState(false); // 弹出层(租金)
  const [vesearch, setVesearch] = useState<[]>([]); // 存放车型信息
  // 获取门店信息
  const get = async () => {
    const data = await getStore();
    setStore(data.data.data);
  };
  // 获取车型信息
  const getVe = async () => {
    const data = await getVesearch();
    setVesearch(data.data.data);
  };
  // 关闭(添加修改)弹框
  const hideModal = () => {
    setOpen(false);
  };
  // 获取到添加的数据
  const onFinish = async (values: any) => {
    const vstatusValue = values.vstatus ? 1 : 0;
    if (editMode) {
      values = { ...values, vstatus: vstatusValue };
      await updateVehicle(
        values,
        previewImage,
        previewImage1,
        previewImage2,
        id
      );
    } else {
      values = { ...values, vstatus: vstatusValue };
      await addVehicle(values, previewImage, previewImage1, previewImage2);
    }
    setOpen(false);
    sousuo();
  };
  // 获取到修改的租金数据
  const onFinishs = async (values: any) => {
    await updateVehicleRent(values,id)
    setRentVisible(false);
  };
  const handleCancel = () => setPreviewOpen(false);
  const handleCancel1 = () => setPreviewOpen1(false);
  const handleCancel2 = () => setPreviewOpen2(false);
  // 上传图片1
  const handleChange: UploadProps["onChange"] = async ({
    fileList: newFileList,
  }: {
    fileList: UploadFile[];
  }) => {
    setFileList(newFileList);
    if (newFileList[0]?.status === "done") {
      const formData = new FormData();
      formData.append("image", newFileList[0].originFileObj as File);
      const response = await uploadImage(formData);
      const imageUrlFromServer = response.data.path;
      setPreviewImage(imageUrlFromServer);
    }
  };
  // 上传图片2
  const handleChange1: UploadProps["onChange"] = async ({
    fileList: newFileList,
  }: {
    fileList: UploadFile[];
  }) => {
    setFileList1(newFileList);
    if (newFileList[0].status === "done") {
      const formData = new FormData();
      formData.append("image", newFileList[0].originFileObj as File);
      const response = await uploadImage(formData);
      const imageUrlFromServer = response.data.path;
      setPreviewImage1(imageUrlFromServer);
    }
  };
  // 上传图片3
  const handleChange2: UploadProps["onChange"] = async ({
    fileList: newFileList,
  }: {
    fileList: UploadFile[];
  }) => {
    setFileList2(newFileList);
    if (newFileList[0].status === "done") {
      const formData = new FormData();
      formData.append("image", newFileList[0].originFileObj as File);
      const response = await uploadImage(formData);
      const imageUrlFromServer = response.data.path;
      setPreviewImage2(imageUrlFromServer);
    }
  };
  // 添加
  const showAddModal = () => {
    setOpen(true);
    setEditMode(false);
    setSelectedRecord(null);
  };
  // 修改回填
  const showEditModal = (record: DataType, id: any) => {
    setId(id);
    setOpen(true);
    setEditMode(true);
    setSelectedRecord(record);
  };
  // 弹出层(删除)
  const Delete = (id: any) => {
    setId(id);
    setDelVisible(true);
  };
  // 关闭弹出层(删除)
  const hideDelModal = () => {
    setDelVisible(false);
  };
  // 关闭弹出层(租金)
  const hideRentModal = () => {
    setRentVisible(false);
  };
  // 删除数据
  const delVehicle = async () => {
    await deleteVehicle(id)
    setDelVisible(false);
    sousuo();
  };
  // 搜索(车型名)
  const onChange = _.debounce((value: any) => {
    setName(value.target.value);
  }, 500);
  // 搜索(状态)
  const onSelectChange = (value: string) => {
    setVstatus(value);
  };
  // 搜索(门店)
  const onSelectChange1 = (value: string) => {
    setSid(value);
  };
  // 初始值
  const sousuo = async () => {
    const { data } = await getVehicle(name,vstatus,sid)
    const updatedList = data.data.map((item: { veid: any }) => ({
      ...item,
      key: item.veid,
    }));
    setList(updatedList);
  };
  // 获取当前id(租金)
  const hideRent = (id: any) => {
    setId(id);
    setRentVisible(true);
  };
  useEffect(() => {
    get();
    getVe();
    getVesearch();
    setSpinning(true);
    setTimeout(() => {
      setSpinning(false);
    }, 1000);
  }, []);
  useEffect(() => {
    sousuo();
  }, [name, vstatus, sid]);

  return (
    <div className="storeBigBox">
      <Spin spinning={spinning} tip="Loading...">
        <Header title="车辆管理" />
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          layout="inline"
          style={{ marginTop: "5px", marginLeft: "10px" }}
        >
          <Form.Item name="name" label="搜索车型" style={{ width: "300px" }}>
            <Input
              placeholder="请输入内容"
              onChange={(value) => onChange(value)}
            />
          </Form.Item>
          <Form.Item name="vstatus" label="运营状态" style={{ width: "300px" }}>
            <Select
              placeholder="请选择状态"
              onChange={(value) => onSelectChange(value)}
            >
              <Select.Option key="true" value="1">
                租凭中
              </Select.Option>
              <Select.Option key="false" value="0">
                未租凭
              </Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="sid" label="所属门店" style={{ width: "300px" }}>
            <Select
              placeholder="请选择门店"
              onChange={(value) => onSelectChange1(value)}
            >
              {store.map((item: any) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
        <div className="storeContent">
          <Button
            type="primary"
            style={{ float: "right", marginBottom: "10px" }}
            onClick={showAddModal}
          >
            添加车辆
          </Button>
          <div className="num">总计:{list.length}</div>
          <Table columns={columns} dataSource={list}  pagination={{
              defaultPageSize: 3, //默认煤业显示条数
              defaultCurrent: 1, //默认当前页数第一页
              pageSizeOptions: ["3", "5", "10"], //每页显示多少条
              locale: {
                items_per_page: "条/页",
              },
            }}/>
        </div>
        {/* 添加修改 */}
        <Modal
          title={editMode ? "编辑车辆" : "添加车辆"}
          visible={open}
          onCancel={hideModal}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
          width="800px"
          bodyStyle={{
            maxHeight: "70vh",
            overflowY: "auto",
            overflowX: "hidden",
          }}
        >
          <VehicleForm
            vesearch={vesearch}
            previewOpen={previewOpen}
            setPreviewOpen={setPreviewOpen}
            previewOpen1={previewOpen1}
            handleCancel1={handleCancel1}
            setPreviewOpen1={setPreviewOpen1}
            previewOpen2={previewOpen2}
            handleCancel2={handleCancel2}
            setPreviewOpen2={setPreviewOpen2}
            editMode={editMode}
            onFinish={onFinish}
            previewImage={previewImage}
            handleChange={handleChange}
            fileList={fileList}
            setFileList={setFileList}
            previewImage1={previewImage1}
            handleChange1={handleChange1}
            fileList1={fileList1}
            setFileList1={setFileList1}
            previewImage2={previewImage2}
            handleChange2={handleChange2}
            fileList2={fileList2}
            setFileList2={setFileList2}
            handleCancel={handleCancel}
            selectedRecord={selectedRecord}
            // 门店信息
            Store={store}
          />
        </Modal>
        {/* 删除 */}
        <Modal
          title="删除车辆"
          visible={delVisible}
          onCancel={hideDelModal}
          footer={null}
          centered
          width="400px"
        >
          <div className="del-modal">
            <p className="del-message">确定要删除该车辆吗？</p>
            <div className="del-modal-btn">
              <Button onClick={hideDelModal} className="simple-btn cancel-btn">
                取消
              </Button>
              <Button
                type="primary"
                onClick={delVehicle}
                className="simple-btn confirm-btn"
              >
                确定
              </Button>
            </div>
          </div>
        </Modal>
        {/* 租金设置 */}
        <Modal
          title="租金设置"
          visible={rentVisible}
          onCancel={hideRentModal}
          footer={null}
          centered
          width="800px"
        >
          <Form
            name="validate_other"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
            onFinish={onFinishs}
            style={{ minWidth: 600 }}
            layout="horizontal"
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="rentaltime"
                  label="租车时间"
                  rules={[{ required: true }]}
                  style={{ marginTop: "50px" }}
                >
                  <DatePicker style={{ width: 200 }} />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  name="rental"
                  label="租金"
                  rules={[{ required: true }]}
                  style={{ marginTop: "50px" }}
                >
                  <Input placeholder="请输入内容" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="cashpledge"
                  label="押金"
                  rules={[{ required: true }]}
                  style={{ marginTop: "30px" }}
                >
                  <Select placeholder="请选择状态">
                    <Select.Option key="0" value="500">
                      500
                    </Select.Option>
                    <Select.Option key="1" value="1000">
                      1000
                    </Select.Option>
                    <Select.Option key="2" value="1500">
                      1500
                    </Select.Option>
                    <Select.Option key="3" value="2000">
                      2000
                    </Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="exceedtime"
                  label="超时服务费"
                  rules={[{ required: true }]}
                  style={{ marginTop: "30px" }}
                >
                  <Input placeholder="请输入内容" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              wrapperCol={{ span: 18, offset: 6 }}
              style={{ marginLeft: "120px", marginTop: "40px" }}
            >
              <Space>
                <Button htmlType="submit" onClick={() => hideRentModal()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Spin>
    </div>
  );
}
